package com.duolaibei.business.base;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.duolaibei.business.R;
import com.duolaibei.business.utils.FragmentManager;
import com.duolaibei.business.utils.SysUtil;
import com.duolaibei.business.utils.inject.InjectUtil;
import com.duolaibei.business.view.App;
import com.duolaibei.business.view.activity.LoginModeActivity;
import com.duolaibei.business.view.dialog.CustomProgressDialog;
import com.gyf.barlibrary.ImmersionBar;

/**
 * Created by xlm on 2017/10/26 0026
 */

public abstract class BaseActivity extends AppCompatActivity
        implements View.OnClickListener {
    private BaseActivity mThis;
    private BaseFragment mCurrentFragment;
    protected ImmersionBar mImmersionBar;

    /**
     * 直接跳转
     *
     * @param cls
     */
    public void startActivity(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        onGetIntent(getIntent());
        super.onCreate(savedInstanceState);
        mThis = this;
        //添加activity到stack中
        App.getApp().addActivity(mThis);
        onSetContentView();
//        //初始化沉浸式
//        if (isImmersionBarEnabled())
//            initImmersionBar();
        if (mThis instanceof LoginModeActivity) {
            setTranslucentStatus();
        }
        injectView();
        initViews();
        beforeOnCreate();
        afterOnCreate(savedInstanceState);
        onSetListener();
    }


    public void beforeOnCreate() {

    }

    private boolean overridePending = false;
    private boolean isFirst = true;

    public void setOverridePending(boolean override) {
        overridePending = override;
    }

    @Override
    protected void onResume() {
//        if (!overridePending) {
//            if (isFirst) {
//                overridePendingTransition(R.anim.in_activity_rtl, R.anim.out_activity_ltr);
//            } else {
//                overridePendingTransition(R.anim.in_back_activity_rtl, R.anim.out_back_activity_ltr);
//            }
//            isFirst = false;
//        }
//        //初始化沉浸式
//        if (isImmersionBarEnabled())
//            initImmersionBar();
        super.onResume();
    }

    /**
     * 设置透明状态栏
     */
    private void setTranslucentStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0 全透明实现
            Window window = getWindow();
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else {//4.4 全透明状态栏
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
        }
    }

//    /**
//     * 是否可以使用沉浸式
//     * Is immersion bar enabled boolean.
//     *
//     * @return the boolean
//     */
//    protected boolean isImmersionBarEnabled() {
//        return true;
//    }

//    /**
//     * 初始化沉浸式
//     */
//    protected void initImmersionBar() {
//        //在BaseActivity里初始化
//        mImmersionBar = ImmersionBar.with(this);
//        mImmersionBar.init();
//        if (mThis instanceof LoginModeActivity) {
//            mImmersionBar.fitsSystemWindows(false).statusBarColor(R.color.transparent).init();
//        } else
//            mImmersionBar.fitsSystemWindows(true).statusBarColor(R.color.orangered).init();
//    }

    /**
     * 通过注解自动绑定资源ID
     */
    private void injectView() {
        InjectUtil.injectActivityFields(this, false);
    }

    /**
     * activity上下文
     *
     * @return
     */
    public BaseActivity getThis() {
        return mThis;
    }

    /**
     * 加载fragment
     *
     * @param framlayout
     * @return
     */
    public FragmentManager initFragmentManager(int framlayout) {
        return new FragmentManager(getThis(), framlayout);
    }

    public void setCurrentFragment(BaseFragment fragment) {
        mCurrentFragment = fragment;
    }

    public BaseFragment getCurrentFragment() {
        return mCurrentFragment;
    }

    /**
     * 获取传递的intent
     *
     * @param intent
     */
    protected void onGetIntent(Intent intent) {

    }

    @Override
    protected void onDestroy() {
//        ImmersionBar.with(mThis).destroy();
        hideSoftInput();
        super.onDestroy();
    }

    //隐藏软键盘
    public void hideSoftInput() {
        View view = getCurrentFocus();
        if (view != null) {
            SysUtil.hideSoftInput(view);
        }
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 返回键
     */
    protected void afterBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onBackPressed() {
        if (mCurrentFragment != null) {
            mCurrentFragment.onBackPressed();
            return;
        }
        afterBackPressed();
    }

    private Toast mToast;

    /**
     * Toast展示
     *
     * @param msg
     */
    public void showToast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mToast != null) {
                    mToast.cancel();
                    mToast = null;
                }
                View layout = getLayoutInflater().inflate(R.layout.toast_custom, (ViewGroup) findViewById(R.id.rl_toast));
                TextView text = layout.findViewById(R.id.toast_content);
                text.setText(msg);
                mToast = new Toast(getThis());
                mToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 240);
                mToast.setDuration(Toast.LENGTH_SHORT);
                mToast.setView(layout);
                mToast.show();
            }
        });
    }

    private CustomProgressDialog mCustomProgressDialog;

    /**
     * 展示加载dialog
     *
     * @param msg
     */
    public void showLoading(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mCustomProgressDialog == null) {
                        mCustomProgressDialog = new CustomProgressDialog(getThis());
                    }
                    mCustomProgressDialog.setMessage(msg);
                    mCustomProgressDialog.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 取消加载dialog
     */
    public void dismissLoading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mCustomProgressDialog != null
                            && mCustomProgressDialog.isShowing()) {
                        mCustomProgressDialog.dismiss();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private ProgressDialog mProgressDialog;

    /**
     * 下载dialog
     *
     * @param msg
     * @return
     */
    private ProgressDialog getProgressDialog(String msg) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(BaseActivity.this);
        }
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setMessage(msg);
        return mProgressDialog;
    }

    /**
     * 下载进度dialog
     *
     * @param msg
     */
    public void showDownProgress(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    getProgressDialog(msg).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 取消下载dialog
     */
    public void dismissDownProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mProgressDialog != null && mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    protected abstract void onSetContentView();//初始化布局文件

    protected abstract void initViews();//绑定view

    protected abstract void afterOnCreate(Bundle savedInstanceState);//事件操作

    protected abstract void onSetListener();//设置监听

    /**
     * 检查内存卡权限
     *
     * @param request_code
     * @return
     */
    public boolean checkStoragePermission(int request_code) {
        int permissionr = 0;
        permissionr = ActivityCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE);
        int permissionw = ActivityCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionr == PackageManager.PERMISSION_GRANTED
                && permissionw == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = new String[0];
            PERMISSIONS_STORAGE = new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };
            ActivityCompat.requestPermissions(getThis(), PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    /**
     * 摄像头
     *
     * @param request_code
     * @return
     */
    public boolean checkCameraPermission(int request_code) {
        int permission = ActivityCompat.checkSelfPermission(getThis(),
                Manifest.permission.CAMERA);
        if (permission == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = {
                    Manifest.permission.CAMERA
            };
            ActivityCompat.requestPermissions(getThis(), PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    /**
     * 录音
     *
     * @param request_code
     * @return
     */
    public boolean checkRecordAudioPermission(int request_code) {
        int permission = ActivityCompat.checkSelfPermission(getThis(),
                Manifest.permission.RECORD_AUDIO);
        if (permission == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = {
                    Manifest.permission.RECORD_AUDIO
            };
            ActivityCompat.requestPermissions(getThis(), PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    /**
     * 地图定位
     *
     * @param request_code
     * @return
     */
    public boolean checkLocationPermission(int request_code) {
        int permissionf = ActivityCompat.checkSelfPermission(getThis(),
                Manifest.permission.ACCESS_FINE_LOCATION);
        int permissionc = ActivityCompat.checkSelfPermission(getThis(),
                Manifest.permission.ACCESS_COARSE_LOCATION);
        if (permissionf == PackageManager.PERMISSION_GRANTED
                && permissionc == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = {
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            };
            ActivityCompat.requestPermissions(getThis(), PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    /**
     * 通讯录权限
     *
     * @param request_code
     * @return
     */
    public boolean checkReadPhoneStatePermission(int request_code) {
        int permissionf = ActivityCompat.checkSelfPermission(this,
                Manifest.permission.READ_PHONE_STATE);
        if (permissionf == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_PHONE_STATE};
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (permissions[0]) {
            case Manifest.permission.READ_EXTERNAL_STORAGE:
            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    onStoragePermission(requestCode, true);
                } else {
                    onStoragePermission(requestCode, false);
                }
                break;
            case Manifest.permission.CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onCameraPermission(requestCode, true);
                } else {
                    onCameraPermission(requestCode, false);
                }
                break;
            case Manifest.permission.RECORD_AUDIO:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onRecordAudioPermission(requestCode, true);
                } else {
                    onRecordAudioPermission(requestCode, false);
                }
                break;
            case Manifest.permission.ACCESS_FINE_LOCATION:
            case Manifest.permission.ACCESS_COARSE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    onLocationPermission(requestCode, true);
                } else {
                    onLocationPermission(requestCode, false);
                }
                break;
            case Manifest.permission.READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onReadPhoneStatePermission(requestCode, true);
                } else {
                    onReadPhoneStatePermission(requestCode, false);
                }
                break;
        }
    }

    public void onStoragePermission(int result_code, boolean result) {

    }

    public void onCameraPermission(int result_code, boolean result) {

    }

    public void onRecordAudioPermission(int result_code, boolean result) {

    }

    public void onLocationPermission(int result_code, boolean result) {

    }

    public void onReadPhoneStatePermission(int result_code, boolean result) {

    }


}
